package com.eva.core.job;

import com.eva.dao.system.model.SystemJob;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 分发器父类，所有分发器继承该父类
 * @author Caesar Liu
 * @date 2022-02-24 11:23
 */
public abstract class BaseDistributer<T> {

    /**
     * 获取业务数据
     * @param jobParam JOB参数
     * @return
     */
    public abstract List<T> getBusinessData(JobParam jobParam);

    /**
     * 获取job分片数据
     * @param dto 分发参数
     * @param jobParam JOB参数
     * @return
     */
    public List<List<T>> getSnippetData (DistributeDTO dto, JobParam jobParam) {
        List<List<T>> snippetData = new ArrayList<>();
        List<T> allData = this.getBusinessData(jobParam);
        int snippetCount = allData.size() / dto.getLimit();
        if (allData.size() % dto.getLimit() > 0) {
            snippetCount++;
        }
        for (int i = 0 ; i < snippetCount; i++) {
            int endLimit = dto.getLimit() * (i + 1);
            if (endLimit >= allData.size()) {
                endLimit = allData.size();
            }
            snippetData.add(allData.subList(dto.getLimit() * i, endLimit));
        }
        return snippetData;
    }

    /**
     * 分发参数
     */
    @Data
    @AllArgsConstructor
    public static class DistributeDTO {

        // 数据限制
        private Integer limit;
    }
}
